package cn.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.WeakHashMap;

public class DAServerSocketChannel extends Thread {
	private ServerSocketChannel server = null;
	public static Map<String, SocketChannel> userHash = null;
	public static Selector selector = null;
	public static LinkedList<String> msgList = null;
	private boolean start = true;

	public DAServerSocketChannel(int port) {
		userHash = new WeakHashMap<String, SocketChannel>();
		userHash = Collections.synchronizedMap(userHash);
		msgList = (LinkedList<String>) Collections
				.synchronizedList(new LinkedList<String>());
		try {
			this.server = ServerSocketChannel.open();
			selector = Selector.open();
			server.socket().bind(new InetSocketAddress(port));
			server.configureBlocking(false);
			server.register(selector, SelectionKey.OP_READ);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public DAServerSocketChannel() {
		int port = 8888;
		userHash = new WeakHashMap<String, SocketChannel>();
		userHash = Collections.synchronizedMap(userHash);
		msgList = (LinkedList<String>) Collections
				.synchronizedList(new LinkedList<String>());
		try {
			this.server = ServerSocketChannel.open();
			selector = Selector.open();
			server.socket().bind(new InetSocketAddress(port));
			server.configureBlocking(false);
			server.register(selector, SelectionKey.OP_READ);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public void run() {
		SocketChannel channel = null;
		try {
			new Listenner().start();
			while (start) {
				channel = this.server.accept();
				channel.register(DAServerSocketChannel.selector,
						SelectionKey.OP_READ);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (channel != null) {
					channel.close();
					channel = null;
				}
				if (this.server != null) {
					server.close();
					server = null;
				}
				if (DAServerSocketChannel.userHash != null) {
					DAServerSocketChannel.userHash.clear();
				}
				if (DAServerSocketChannel.msgList != null) {
					DAServerSocketChannel.msgList.clear();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	public int startServer() {
		this.start();
		return 1;
	}

	public int stioServer() {
		this.start = false;
		try {
			this.server.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1;
	}
}
